import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../../app/store';
import { Order } from './domain.model';

export interface OrdersState {
  ordersList: Order[];
  status: 'idle' | 'loading' | 'failed';
};
  
const initialState: OrdersState = {
   ordersList: [],
   status: 'idle',
};

// редакс тулкит делает так:
// function updateMyOrder(payload: OrdersState) {
//   return {
//     type: 'updateMyOrder',
//     payload
//   }
// };

export const ordersSlice = createSlice({
  name: 'orders',
  initialState,
  reducers: {
    updateOrder: (state, action: PayloadAction<Order>) => {
      state.ordersList.push(action.payload);
    },
  },
});

export const selectOrders = (state: RootState) => state.orders.ordersList;
export const selectOrderById = (state: RootState, orderId: string): Order => {
  const currentOrder: Order | undefined = state.orders.ordersList.find((order) => order.id === orderId);
  if (currentOrder) {
    return currentOrder;
  } else {
    throw new Error('selectOrderById: unable to find order');
  }
}
export const selectOrdersByIds = (state: RootState, ids: string[]): Order[] => ids.map((id) => selectOrderById(state, id));

export const { updateOrder } = ordersSlice.actions;

export default ordersSlice.reducer;